<template>
  <div class="lyric"
       v-if="lyric!=''">
    <scroll class="lyric-scroll"
            ref="scroll">
      <ul>
        <!-- 歌词 -->
        <li v-for="(item,index) in lyricArray"
            :key="index"
            :class="{action:index==lyricIndex}">
          {{item.lyric}}</li>
      </ul>
    </scroll>
  </div>
</template>

<script>
import Scroll from "components/common/scroll/Scroll"
import { LyricItem } from "./playList"
export default {
  name: 'Lyric',
  components: {
    Scroll
  },
  props: {
    lyric: {
      type: String,
      default () {
        return ''
      }
    }
  },
  data () {
    return {
      // 歌词列表
      lyricArray: [],
      // 当前显示歌词的下标
      lyricIndex: -1,
      // ？
      maxIndex: 0,
      length: 0
    }
  },
  watch: {
    lyric () {
      this.lyricIndex = -1;
      this.maxIndex = 0;
      this.parseLyric(this.lyric)
    }
  },
  methods: {
    parseLyric (lyric) {
      // 正则匹配歌词
      const RegExp = /\[(\d*:\d*\.\d*)\]/;
      let arr = []
      const timeArr = []
      const lyricArr = []
      const mergeArr = []
      //   将歌词准化成数组
      arr = lyric.split('\n')
      for (const i of arr) {
        const lrc = i.split(']')[1]
        if (lrc === '' || lrc === undefined) continue
        lyricArr.push(lrc)

        // 将每句歌词对应的时间，格式化成秒数
        const resTime = RegExp.exec(i)[1];
        const resTime2 = resTime.split(':')
        const min = parseInt(resTime2[0]) * 60
        const sec = parseFloat(resTime2[1])
        const time = parseFloat(Number(min + sec).toFixed(2)) //  toFixed返回值是String
        timeArr.push(time)
      }
      for (let i = 0, length = timeArr.length; i < length; i++) {
        const obj = new LyricItem(timeArr[i], lyricArr[i])
        mergeArr.push(obj)
      }
      //  歌词按时间升序
      this.lyricArray = mergeArr.sort((a, b) => {
        return a.time - b.time
      })
      this.length = this.lyricArray.length
    },
    // 歌词滚动
    scrollLyric (time = 0) {
      if (this.lyricIndex > this.length - 2) return;
      //  如果传入的时间比当前显示的歌词时间大，意味着需要跳转到time对应的歌词
      if (time >= this.lyricArray[this.lyricIndex + 1].time) {
        this.lyricIndex++;
        this.$refs.scroll.scrollTo(0, -30 * this.lyricIndex, 2000);
      }
    },
    maxScroll (time = 0) {
      if (this.lyricIndex > this.length - 2) return;
      if (time >= this.lyricArray[this.lyricIndex + 1].time) {
        this.lyricIndex++;
        // 如果当前歌词下标小于5，则不需要改变显示的所有歌词（在屏幕上一次显示5条）
        if (this.lyricIndex < 5 || this.lyricIndex >= this.lyricArray.length - 5) return
        this.maxIndex++;
        this.$refs.scroll.scrollTo(0, -30 * this.maxIndex, 2000)
      }
    }

  }
}
</script>

<style scoped>
.lyric-scroll {
  height: 100%;
  overflow: hidden;
}
.lyric ul {
  text-align: center;
  list-style-type: none;
}
.lyric ul li {
  height: 30px;
  box-sizing: border-box;
  padding: 5px 0px;
}
.action {
  font-size: 18px;
  color: #00aa85;
}
</style>
